package com.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 71. 简化路径
 * 堆栈法
 *
 * @author fy
 * @date 2022/4/12 17:56
 */
public class Solution71 {

    public String simplifyPath(String path) {
        if (path == null || path.length() == 0) {
            return path;
        }
        String[] arr = path.split("/");
        // printArr(arr);
        Deque<String> stack = new LinkedList<>();
        for (String s : arr) {
            if ("".equals(s) || ".".equals(s)) {
                continue;
            }
            if ("..".equals(s)) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                stack.push(s);
            }
        }
        StringBuilder sb = new StringBuilder();
        if (stack.isEmpty()) {
            sb.append("/");
        } else {
            while (!stack.isEmpty()) {
                sb.append("/").append(stack.pollLast());
            }
        }
        return sb.toString();
    }

    private void printArr(String[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            String s = arr[i];
            if (i == arr.length - 1) {
                System.out.print(s);
            } else {
                System.out.print(s + ", ");
            }
        }
        System.out.print("]");
        System.out.println();
    }


    public static void main(String[] args) {
//        String path = "/a/./b/../../c/";
        String path = "/home//foo/";
//        String path = "/../";
//        String path = "/home/";
        String res = new Solution71().simplifyPath(path);
        System.out.println(res);
    }

}
